import math
import numpy as np
co_num = []
code_k=[]
arr=input('请键入您的信源概率:').split(',')
an = np.array(arr)
num = an.astype(np.float64)#将字符型数组转化为浮点型数组

def sort():#将数组从大到小排序
    n=len(num)
    for i in range(n):
        for j in range(1, n-i):
            if  num[j-1] <=num[j] :
                num[j-1],num[j] =num[j], num[j-1]
    return num

def c_num():#计算累积概率
    k=0
    co_num.append(0)
    for i in range (0,len(num)-1):
        k+=num[i]
        co_num.append(round(k,2))
    return co_num

def code_length():#求码长数组
    f=0
    for i in range(len(num)):
        code_k.append(int(math.log(num[i], 2) * (-1) + 1))
    return code_k

def er_code(numx):#二进制转换函数，#乘2取整，顺序排列
    b = []
    while True:
        numx *= 2
        b.append(1 if numx>= 1 else 0)
        numx -= int(numx)
        if numx == 0:
            for i in range(len(num)):
                if len(b) != code_k[i]:
                    b.append('0' * (code_k[i] - len(b)))
            break
    return b

def u_code():
    code = []  # 对应码字
    for i in range(len(num)):
        e = ''
        for j in range(code_k[i]):
            e += str(er_code(co_num[i])[j])
        code.append(e)
    return code

def ave_code():#求平均码长
    p=0
    for i in range (len(code_k)):
        p+=code_k[i]*num[i]
    return p

def H():#算信源熵
   h=0
   for i in range (len(num)):
       h+=num[i]*math.log(num[i],2)*(-1)
   return h

def eff():  # 编码效率
    e = H() / ave_code()
    return e

def PrintArr():#打印各类数组结果
    print('排序后的信源概率为：{}'.format(num))
    print('累加信源概率为：{}'.format(co_num))
    print('各符号码字长度为：{}'.format(code_k))
    print('各符号码字为：{}'.format(u_code()))
    print("平均码长为：{:.3}(bit/symbol)".format(ave_code()))
    print("信源熵为：{:.3}(bit/symbol)".format(H()))
    print('编码效率为：{:.3}%'.format(eff()*100))

#调用函数开始执行
numx=num.all()
sort()
c_num()
code_length()
er_code(numx)
u_code()
ave_code()
eff()
PrintArr()

#0.2,0.19,0.18,0.17,0.15,0.1,0.01
